﻿namespace Harness.Commands
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Net;

    internal class DownloadCommand : ICommand
    {
        #region Constants

        private const int UrlArgIndex = 0;
        private const int FilenameArgIndex = 1;

        #endregion

        #region Public Methods

        public void SyntaxCheck(IHarness harness, IEnumerable<object> args)
        {
            if (null == args.ElementAtOrDefault(UrlArgIndex))
            {
                throw new ArgumentNullException((UrlArgIndex + 1).ToString() + ":url");
            }

            if (null == args.ElementAtOrDefault(FilenameArgIndex))
            {
                throw new ArgumentNullException((FilenameArgIndex + 1).ToString() + ":filename");
            }
        }

        public dynamic Execute(IHarness harness, IEnumerable<object> args)
        {
            Uri url = new Uri((args.ElementAtOrDefault(UrlArgIndex) ?? string.Empty).ToString());
            string filename = (args.ElementAtOrDefault(FilenameArgIndex) ?? string.Empty).ToString();

            using (WebClient webClient = new WebClient())
            {
                webClient.DownloadFile(url, filename);
            }

            return null;
        }

        #endregion
    }
}
